<template>
  <div class="min-h-screen bg-gray-50 dark:bg-gray-900 py-8 px-4 sm:px-6 md:px-8 lg:px-12">
    <div class="w-full">
      <!-- 搜索框 -->
      <div class="mb-10 mt-10">
        <div class="max-w-2xl mx-auto">
          <div class="relative">
            <!-- 搜索输入框 -->
            <div
              class="relative bg-white dark:bg-gray-800 rounded-lg shadow-lg border border-gray-200 dark:border-gray-600"
            >
              <div class="flex items-center px-4 py-3">
                <!-- 当前搜索引擎图标 -->
                <div
                  class="flex items-center space-x-3 flex-shrink-0 cursor-pointer"
                  @click="toggleSearchEngines"
                >
                  <div :class="`w-8 h-8 rounded-full flex items-center justify-center`">
                    <!-- 动态显示当前搜索引擎图标 -->
                    <img
                      v-if="getCurrentEngineIcon().startsWith('http')"
                      :src="getCurrentEngineIcon()"
                      :alt="getCurrentEngineTitle()"
                      class="w-6 h-6 object-contain"
                    />
                    <div
                      v-else
                      :class="`w-6 h-6 ${getCurrentEngineColor()} rounded flex items-center justify-center`"
                    >
                      <span class="text-white text-xs font-bold">{{ getCurrentEngineIcon() }}</span>
                    </div>
                  </div>
                  <div class="flex space-x-1">
                    <div class="w-1 h-1 bg-red-500 rounded-full"></div>
                    <div class="w-1 h-1 bg-blue-500 rounded-full"></div>
                  </div>
                </div>

                <!-- 搜索输入框 -->
                <input
                  v-model="searchQuery"
                  type="text"
                  placeholder="输入关键词搜索"
                  class="flex-1 ml-4 bg-transparent border-none outline-none text-gray-700 dark:text-gray-200 placeholder-gray-400 dark:placeholder-gray-500 text-base"
                  @keydown.enter="performSearch"
                />

                <!-- 搜索按钮 -->
                <button
                  @click="performSearch"
                  class="ml-3 px-4 py-2 bg-blue-500 hover:bg-blue-600 text-white rounded-lg transition-colors"
                >
                  搜索
                </button>
              </div>
            </div>

            <!-- 搜索引擎选择弹窗 -->
            <div
              v-if="showSearchEngines"
              class="absolute top-full left-0 right-0 mt-2 bg-white dark:bg-gray-800 rounded-lg shadow-xl border border-gray-200 dark:border-gray-600 z-50"
            >
              <div class="p-4">
                <div class="grid grid-cols-6 gap-3">
                  <div
                    v-for="engine in searchEngines"
                    :key="engine.id"
                    @click="selectSearchEngine(engine.id)"
                    class="flex flex-col items-center p-2 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 cursor-pointer transition-colors relative"
                    :class="{ 'bg-blue-50 dark:bg-blue-900/20': currentSearchEngine === engine.id }"
                  >
                    <div class="w-8 h-8 rounded-lg flex items-center justify-center mb-1">
                      <!-- 如果是图片URL，显示图片；否则显示文字 -->
                      <img
                        v-if="engine.icon.startsWith('http')"
                        :src="engine.icon"
                        :alt="engine.title"
                        class="w-6 h-6 object-contain"
                      />
                      <div
                        v-else
                        :class="`w-6 h-6 ${searchEngineColors[engine.id]} rounded flex items-center justify-center`"
                      >
                        <span class="text-white text-xs font-bold">{{ engine.icon }}</span>
                      </div>
                    </div>
                    <span
                      class="text-xs"
                      :class="
                        currentSearchEngine === engine.id
                          ? 'text-blue-600 dark:text-blue-400'
                          : 'text-gray-600 dark:text-gray-400'
                      "
                      >{{ engine.title }}</span
                    >
                    <!-- 选中标记 -->
                    <div
                      v-if="currentSearchEngine === engine.id"
                      class="absolute top-1 right-1 w-3 h-3 bg-blue-500 rounded-full flex items-center justify-center"
                    >
                      <svg class="w-1.5 h-1.5 text-white" fill="currentColor" viewBox="0 0 24 24">
                        <path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z" />
                      </svg>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 动态工具部分 -->
      <section v-for="section in toolSections" :key="section.id" class="mb-16">
        <div class="flex items-center mb-6">
          <div class="w-3 h-3 bg-gray-400 rounded mr-3"></div>
          <h2 class="text-lg md:text-xl font-bold text-gray-800 dark:text-gray-100">
            {{ section.title }}
          </h2>
        </div>
        <div
          class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 2xl:grid-cols-6 gap-4"
        >
          <div
            v-for="tool in section.tools"
            :key="tool.id"
            class="relative bg-white dark:bg-gray-800 rounded-lg shadow-md hover:shadow-xl hover:-translate-y-1 transition-all duration-300 p-3 group cursor-pointer border border-gray-100 dark:border-gray-700 hover:border-blue-200 dark:hover:border-blue-700"
            @click="handleToolClick(tool)"
          >
            <!-- 卡片内容 -->
            <div class="flex items-center space-x-3">
              <!-- 图标 -->
              <div class="w-10 h-10 flex items-center justify-center flex-shrink-0 overflow-hidden">
                <img
                  v-if="tool.icon && tool.icon.startsWith('http')"
                  :src="tool.icon"
                  :alt="tool.title"
                  class="w-10 h-10 object-cover rounded-lg"
                />
                <span v-else class="text-gray-700 dark:text-gray-200 text-lg font-medium">{{
                  tool.icon
                }}</span>
              </div>

              <!-- 文字内容 -->
              <div class="flex-1 min-w-0">
                <h3
                  class="text-sm font-semibold text-gray-800 dark:text-gray-100 mb-1 leading-tight truncate"
                  :title="tool.title"
                >
                  {{ tool.title }}
                </h3>
                <p
                  class="text-xs text-gray-600 dark:text-gray-400 leading-tight truncate"
                  :title="tool.description"
                >
                  {{ tool.description }}
                </p>
              </div>
            </div>

            <!-- Tooltip 提示 -->
            <div
              class="absolute bottom-full left-1/2 transform -translate-x-1/2 mb-2 px-3 py-2 bg-gray-900 dark:bg-gray-700 text-white text-xs rounded-lg opacity-0 group-hover:opacity-100 transition-opacity duration-200 pointer-events-none z-50 w-max max-w-full break-words"
              :title="tool.description"
            >
              {{ tool.description }}
              <!-- 小三角 -->
              <div
                class="absolute top-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-l-4 border-r-4 border-t-4 border-transparent border-t-gray-900 dark:border-t-gray-700"
              ></div>
            </div>

            <!-- 悬停效果 -->
            <div
              class="absolute inset-0 bg-gradient-to-r from-blue-100/50 to-indigo-100/50 dark:from-blue-900/20 dark:to-indigo-900/20 rounded-lg opacity-0 group-hover:opacity-100 transition-opacity duration-300 pointer-events-none"
            ></div>
          </div>
        </div>
      </section>

      <!-- 加载状态和底部提示 -->
      <div class="text-center py-8">
        <!-- 加载中状态 -->
        <div v-if="loading" class="flex items-center justify-center space-x-2">
          <div
            class="w-4 h-4 border-2 border-blue-500 border-t-transparent rounded-full animate-spin"
          ></div>
          <span class="text-gray-600 dark:text-gray-400">加载中...</span>
        </div>

        <!-- 已到达底部提示 -->
        <div v-else-if="hasReachedBottom" class="text-gray-500 dark:text-gray-400">
          <div class="flex items-center justify-center space-x-2">
            <div class="w-4 h-4 border-2 border-gray-300 rounded-full"></div>
            <span>已到达底部</span>
          </div>
        </div>

        <!-- 暂无数据提示 -->
        <div
          v-else-if="toolSections.length === 0 && !loading"
          class="text-gray-500 dark:text-gray-400"
        >
          暂无工具数据
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { getTool, Tool, ToolVO } from '@/apis/blog/tool'

// 工具分类数据
const toolSections = ref<ToolVO[]>([])

// 分页相关状态
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(false)
const hasReachedBottom = ref(false)

// 搜索相关状态
const searchQuery = ref('')
const showSearchEngines = ref(false)
const currentSearchEngine = ref('baidu') // 默认搜索引擎

// 搜索引擎数据
const searchEngines = ref([
  {
    id: 'google',
    title: 'Google',
    icon: 'https://lf-cdn-tos.bytescm.com/obj/static/xitu_extension/static/google-bordered.2eb88156.png',
    url: 'https://www.google.com'
  },
  {
    id: 'baidu',
    title: '百度',
    icon: 'https://lf-cdn-tos.bytescm.com/obj/static/xitu_extension/static/baidu-bordered.b5a231e3.png',
    url: 'https://www.baidu.com'
  },
  {
    id: 'bing',
    title: 'Bing',
    icon: 'https://lf-cdn-tos.bytescm.com/obj/static/xitu_extension/static/bing-bordered.b21955c6.png',
    url: 'https://www.bing.com'
  },
  {
    id: 'sogou',
    title: '搜狗',
    icon: '搜',
    url: 'https://www.sogou.com'
  },
  {
    id: 'haosou',
    title: '好搜',
    icon: '好',
    url: 'https://www.haosou.com'
  },
  {
    id: 'yandex',
    title: 'Yandex',
    icon: 'Y',
    url: 'https://www.yandex.com'
  },
  {
    id: 'duckduckgo',
    title: 'DuckDuckGo',
    icon: 'D',
    url: 'https://www.duckduckgo.com'
  }
])

// 搜索引擎名称映射
const searchEngineNames = ref({
  google: 'G',
  baidu: '百',
  bing: 'B',
  sogou: '搜',
  haosou: '好',
  yandex: 'Y',
  duckduckgo: 'D'
})

// 搜索引擎颜色映射
const searchEngineColors: Record<string, string> = {
  google: 'bg-blue-600',
  baidu: 'bg-blue-500',
  bing: 'bg-blue-400',
  sogou: 'bg-blue-500',
  haosou: 'bg-blue-400',
  yandex: 'bg-blue-300',
  duckduckgo: 'bg-blue-200'
}

// 切换搜索引擎弹窗显示状态
const toggleSearchEngines = () => {
  showSearchEngines.value = !showSearchEngines.value
}

// 选择搜索引擎
const selectSearchEngine = (engine: string) => {
  currentSearchEngine.value = engine
  showSearchEngines.value = false
}

// 执行搜索
const performSearch = () => {
  if (searchQuery.value.trim()) {
    const engine = searchEngines.value.find(e => e.id === currentSearchEngine.value)
    if (engine) {
      let searchUrl = ''
      if (engine.id === 'google') {
        searchUrl = `https://www.google.com/search?q=${encodeURIComponent(searchQuery.value)}`
      } else if (engine.id === 'baidu') {
        searchUrl = `https://www.baidu.com/s?wd=${encodeURIComponent(searchQuery.value)}`
      } else if (engine.id === 'bing') {
        searchUrl = `https://cn.bing.com/search?q=${encodeURIComponent(searchQuery.value)}`
      } else if (engine.id === 'sogou') {
        searchUrl = `https://www.sogou.com/web?query=${encodeURIComponent(searchQuery.value)}`
      } else if (engine.id === 'haosou') {
        searchUrl = `https://www.so.com/s?q=${encodeURIComponent(searchQuery.value)}`
      } else if (engine.id === 'yandex') {
        searchUrl = `https://yandex.com/search/?text=${encodeURIComponent(searchQuery.value)}`
      } else if (engine.id === 'duckduckgo') {
        searchUrl = `https://duckduckgo.com/?q=${encodeURIComponent(searchQuery.value)}`
      }

      if (searchUrl) {
        window.open(searchUrl, '_blank')
      }
    }
  }
}

// 处理键盘事件
const handleKeydown = (event: KeyboardEvent) => {
  if (event.key === 'Enter') {
    performSearch()
  } else if (event.key === 'Tab') {
    event.preventDefault()
    // 切换到下一个搜索引擎
    const engines = Object.keys(searchEngines)
    const currentIndex = engines.indexOf(currentSearchEngine.value)
    const nextIndex = (currentIndex + 1) % engines.length
    currentSearchEngine.value = engines[nextIndex]
  }
}

// 获取当前搜索引擎的图标
const getCurrentEngineIcon = () => {
  const engine = searchEngines.value.find(e => e.id === currentSearchEngine.value)
  return engine ? engine.icon : ''
}

// 获取当前搜索引擎的标题
const getCurrentEngineTitle = () => {
  const engine = searchEngines.value.find(e => e.id === currentSearchEngine.value)
  return engine ? engine.title : ''
}

// 获取当前搜索引擎的颜色
const getCurrentEngineColor = () => {
  const engine = searchEngines.value.find(e => e.id === currentSearchEngine.value)
  return engine ? searchEngineColors[engine.id] : ''
}

// 获取工具数据
const fetchToolData = async (isLoadMore = false) => {
  if (loading.value) return

  try {
    loading.value = true

    const data = await getTool({
      pageSize: pageSize.value,
      currentPage: currentPage.value
    })

    if (isLoadMore) {
      // 加载更多时，追加数据
      toolSections.value.push(...data.list)
    } else {
      // 首次加载时，替换数据
      toolSections.value = data.list
    }

    total.value = data.total

    // 检查是否已到达底部
    const totalPages = Math.ceil(total.value / pageSize.value)
    hasReachedBottom.value = currentPage.value >= totalPages
  } catch (error) {
    console.error('获取工具数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 加载下一页
const loadNextPage = async () => {
  if (loading.value || hasReachedBottom.value) return

  currentPage.value++
  await fetchToolData(true)
}

// 滚动处理函数
const handleScroll = () => {
  const scrollTop = window.pageYOffset || document.documentElement.scrollTop
  const windowHeight = window.innerHeight
  const documentHeight = document.documentElement.scrollHeight

  // 当滚动到距离底部100px时，触发加载
  if (scrollTop + windowHeight >= documentHeight - 100) {
    loadNextPage()
  }
}

// 处理工具点击事件
const handleToolClick = (tool: Tool) => {
  if (tool.url) {
    // 这里可以根据需要选择跳转方式
    // 方式1: 新窗口打开
    window.open(tool.url, '_blank')

    // 方式2: 当前窗口跳转
    // window.location.href = tool.url

    // 方式3: 使用Vue Router跳转（如果配置了路由）
    // router.push(tool.url)
  }
}

// 重置分页状态
const resetPagination = () => {
  currentPage.value = 1
  hasReachedBottom.value = false
  toolSections.value = []
}

// 组件挂载时获取数据
onMounted(async () => {
  await fetchToolData()
  document.addEventListener('keydown', handleKeydown)
  window.addEventListener('scroll', handleScroll)
})

// 组件卸载时移除事件监听
onUnmounted(() => {
  document.removeEventListener('keydown', handleKeydown)
  window.removeEventListener('scroll', handleScroll)
})
</script>

<style scoped>
/* 自定义样式 */
</style>
